<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { resetPassword } from '@/api/user';
const router = useRouter();

// 表单数据
const formData = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 表单验证规则
const rules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== formData.value.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      }, trigger: 'blur' }
  ]
};

// 表单引用
const formRef = ref(null);

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      resetPassword({
        oldPassword: formData.value.currentPassword,
        newPassword: formData.value.newPassword
      }).then(res => {
        if (res.code === 200) {
          ElMessage.success('密码重置成功，请重新登录');
          router.push('/login');
        }
      }).catch(err => {
        ElMessage.error(err.message || '密码重置失败');
      });
    }
  });
};

// 重置表单
const resetForm = () => {
  formRef.value.resetFields();
};
</script>

<template>
  <el-card class="password-reset-card">
    <h1 class="title">重置密码</h1>
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="当前密码" prop="currentPassword">
        <el-input v-model="formData.currentPassword" type="password" placeholder="请输入当前密码"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="formData.newPassword" type="password" placeholder="请输入新密码"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input v-model="formData.confirmPassword" type="password" placeholder="请确认新密码"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm" style="margin-left: 10px;">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped lang="scss">
.password-reset-card {
  max-width: 500px;
  margin: 50px auto;
  padding: 20px;
}
.title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}
::v-deep .el-form-item {
  margin-bottom: 20px;
}
</style>